package cn.fl.capital.service.impl;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.api.ICapOvdErrLogApiService;
import cn.fl.capital.condition.CapFundVfDtlQueryCondition;
import cn.fl.capital.condition.CapOvdErrLogQueryCondition;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.capital.dto.CapFundVfDtlDTO;
import cn.fl.capital.dto.CapOvdErrLogDTO;
import cn.fl.capital.dto.CapOverdueInfoDTO;
import cn.fl.capital.service.ICapFundVfDtlApiService;
import cn.fl.capital.service.ICapOvdErrLogService;
import cn.fl.capital.service.ICapOverdueInfoApiService;
import cn.fl.capital.transform.CapOvdErrLogVOTransform;
import cn.fl.capital.vo.CapOvdErrLogVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description: 资方逾期异常记录表 客户端服务层接口实现
 * 业务层方法名称前缀：
 * 新增：add*
 * 删除：remove*
 * 修改：modify*
 * 批量：batch*
 * 查询对象：select* get*
 * 查询集合：search*
 */
@Service
public class CapOvdErrLogServiceImpl implements ICapOvdErrLogService {

	/**
     * 日志
     */
    @SuppressWarnings("unused")
    private static final Logger logger = LoggerFactory.getLogger(CapOvdErrLogServiceImpl.class);
	
	/**
	 * 资方逾期异常记录表 暴露服务
	 */
	@Autowired
	private ICapOvdErrLogApiService capOvdErrLogApiService;
	/**
     * 数据字典服务
     */
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

	@Autowired
	private ICapOverdueInfoApiService capOverdueInfoApiService;

	@Autowired
	private ICapFundVfDtlApiService capFundVfDtlApiService;

	@Override
	public CapOvdErrLogVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)) return null;
		CapOvdErrLogDTO dto = this.capOvdErrLogApiService.selectCapOvdErrLogById(id);
		return CapOvdErrLogVOTransform.toVO(dto);
	}

	@Override
	public Long add(CapOvdErrLogVO entity) throws BaseException{
		if(null == entity) return null;
		return this.capOvdErrLogApiService.addCapOvdErrLog(CapOvdErrLogVOTransform.toDTO(entity));
	}

	@Override
	public boolean removeByIds(List<Long> ids) throws BaseException{
		if(CollectionUtils.isEmpty(ids)) return false;
		return this.capOvdErrLogApiService.removeCapOvdErrLogByIds(ids,CurrentThreadContext.getCurrentUserId());
	}

	@Override
	public boolean modify(CapOvdErrLogVO entity) throws BaseException{
		if(null == entity) return false;
		return this.capOvdErrLogApiService.modifyCapOvdErrLog(CapOvdErrLogVOTransform.toDTO(entity));
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
        CapOvdErrLogQueryCondition condition=null;
        if(null == page) {
            page = new Pager();
            page.setCondition(new CapOvdErrLogQueryCondition());
        }
		condition=(CapOvdErrLogQueryCondition)page.getCondition();
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
		page=this.capOvdErrLogApiService.searchCapOvdErrLogListPage(page);
		if(CollectionUtils.isNotEmpty(page.getResultList())){
            List<CapOvdErrLogVO> voList=CapOvdErrLogVOTransform.toVOList((List<CapOvdErrLogDTO>)page.getResultList());
            //this.setDictData(voList);
            page.setResultList(voList);
        }
        return page;
	}
	
	@Override
	public List<CapOvdErrLogVO> searchList(CapOvdErrLogQueryCondition condition) throws BaseException{
		if(null == condition) condition=new CapOvdErrLogQueryCondition();
		condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
		condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
		condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
		List<CapOvdErrLogVO> voList=CapOvdErrLogVOTransform.toVOList(this.capOvdErrLogApiService.searchCapOvdErrLogList(condition));
		this.setDictData(voList);
		return voList;
	}
	
    /**
     * 添加数据字典名称
     * @param voList
     */
	public void setDictData(List<CapOvdErrLogVO> voList){
		if(CollectionUtils.isEmpty(voList)) return;
		/*Map<String, String> _CdMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, CapOvdErrLogConstant.CODE_CD);
		for(CapOvdErrLogVO vo:voList){
			if (_CdMap != null && _CdMap.containsKey(vo.getCd())) {
            	vo.setCdNm(_CdMap.get(vo.getCd()));
        	}	
		}*/
	}
	
	/**
     * 查询数据字典
     * @param groupCd 组代码
     * @return List<KeyValueVO>
     */
    public List<KeyValueVO> searchCdList(String groupCd){
        return this.sysDictionaryApiService.getKvList(groupCd, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
    }

    /**
     * 忽略数据
     */
    @Override
    public boolean ignoreData(Long id) throws BaseException {
        CapOvdErrLogVO entity=new CapOvdErrLogVO();
        entity.setId(id);
        entity.setDataStsCd("3");
        return this.capOvdErrLogApiService.modifyCapOvdErrLog(CapOvdErrLogVOTransform.toDTO(entity));
    }

	@Override
	public Long calculatePenaltyAmt(String calType, Long id, Long paySchId) throws BaseException {
    	Long pAmt = 0l;
		if ("1".equals(calType) || "2".equals(calType)) {
			// 根据主键查询资方逾期异常记录表数据
			CapOvdErrLogDTO capOvdErrLogDTO = capOvdErrLogApiService.selectCapOvdErrLogById(id);
			pAmt = capOvdErrLogDTO.getOvdPenaltyAmt();

			if ("1".equals(calType)) {
				// 次日异常处理：罚息 = 今日更新过来的罚息金额
				return pAmt;
			} else if ("2".equals(calType)) {
				// 跨次日异常处理：罚息 = (1)今日更新过来的罚息金额+(2)本次将要冲红分解单中状态为已推送罚息金额+(3)逾期本金、逾期利息之差（资方逾期租金-我司逾期租金，负数按照0计算）
				// 资方逾期租金
				Long ovdRentAmt = capOvdErrLogDTO.getOvdRentAmt();
				// 我司逾期租金
				CapOverdueInfoDTO capOverdueInfoDTO = capOverdueInfoApiService.selectByPaySchId(paySchId);
				Long overdueAmount = capOverdueInfoDTO == null ? 0 : capOverdueInfoDTO.getOverdueAmount();
				// 计算(3)项，二者相减
				long diffValue = (ovdRentAmt - overdueAmount) < 0 ? 0 : (ovdRentAmt - overdueAmount);

				// 计算(2)项
				Long vfAmt = 0l;
				CapFundVfDtlQueryCondition condition = new CapFundVfDtlQueryCondition();
				condition.setIsDel(BaseConstant.IS_YESNO_NO);
				condition.setPaySchId(paySchId);
				condition.setVfTypCd(CapitalConstant.CODE_VF_TYP_CD_1);
				// 核销状态集合（CAP0004）：2.已分解
				condition.setVfStsCd(CapitalConstant.CODE_CAP_FUND_STS_CD_2);
				// 费用类型：S05-罚息
				condition.setFeeTypCd(CapitalConstant.CODE_FEE_TYP_CD_S05);
				// 三方同步标识 0-未同步 1-已同步
				condition.setThrSyncSts(CapitalConstant.CODE_THR_SYNC_STS_1);
				condition.setSortName("CRT_TM");
				condition.setSortOrder("DESC NULLS LAST");
				List<CapFundVfDtlDTO> capFundVfDtlDTOS = capFundVfDtlApiService.searchCapFundVerificationList(condition);
				if (CollectionUtils.isNotEmpty(capFundVfDtlDTOS)) {
					CapFundVfDtlDTO capFundVfDtlDTO = capFundVfDtlDTOS.get(0);
					vfAmt = capFundVfDtlDTO.getVfAmt();
				}
				pAmt = pAmt + vfAmt + diffValue;
			}
		}
		return pAmt;
	}

	@Override
	public boolean updateBusiProcessing(CapOvdErrLogDTO entity) throws BaseException {
    	entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
    	entity.setMdfUsrNm(CurrentThreadContext.getCurrentUserName());
    	entity.setMdfUsrOrgCd(CurrentThreadContext.getCurrentOrgCd());

		return capOvdErrLogApiService.modifyProcessing(entity);
	}
}
